#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <unistd.h>
#include <stdlib.h>

#include <fcntl.h>
#include <sys/epoll.h>
#include <stdbool.h>

#include "user/login.h"

#define MAX_EVENTS 1024

int main(){
    int sockfds[3];
    uint16_t ports[3] = {9241, 9242, 9243};

    int ep_fd = epoll_create1(0);
    if(ep_fd < 0){
        perror("epoll_create1");
        return -1;
    }
    struct epoll_event ev,  events[MAX_EVENTS];

    for(int i=0;i<3;i++){
        sockfds[i] = socket(AF_INET, SOCK_STREAM, 0);
        struct sockaddr_in addr = {
            .sin_family = AF_INET,
            .sin_port = htons(ports[i]),
            .sin_addr = INADDR_ANY
        };
        if(bind(sockfds[i], (struct sockaddr *)&addr, sizeof(addr)) !=0){
            perror("bind");
            return -1;
        }

        listen(sockfds[i], 10);

        ev.data.fd = sockfds[i];
        ev.events = EPOLLIN;
        epoll_ctl(ep_fd, EPOLL_CTL_ADD, sockfds[i], &ev);
    }

    int fd_n = 0;
    bool issocket = false;
    while(1){
        fd_n = epoll_wait(ep_fd, events, MAX_EVENTS, -1);
        for(int i=0;i<fd_n;i++){
            // 是否是客户端连接
            for(int j=0;j<3;j++){
                if(events[i].data.fd == sockfds[j]){
                    issocket = true; // 三个套接字之一
                    Client_ *client = NULL;
                    switch (j)
                    {
                    case 0:
                        // 处理登录连接
                        client = login_handle(sockfds[j]);
                        if(client == NULL) continue;
                        ev.data.fd = client->fd;
                        ev.data.ptr = client;
                        ev.events = EPOLLIN;

                        epoll_ctl(ep_fd, EPOLL_CTL_ADD, client->fd, &ev);
                        break;
                    case 1: 
                        // 上传文件 连接
                    case 2:
                        // 搜索文件 连接
                        break;
                    }
                }
            }

            // 客户端通信 
            if(!issocket){
                Client_ *client = events[i].data.ptr;
                if(client->reqcode == LOGIN){  // 登录处理
                    if(login(client) ){
                        epoll_ctl(ep_fd, EPOLL_CTL_DEL, client->fd, NULL);
                        free(client);
                    }   
                }

            }
            
        }
    }
    return 0;
}
